package com.laomo.lib_bt.util;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;

import com.jieli.jl_bt_ota.util.CHexConver;
import com.jieli.jl_bt_ota.util.JL_Log;

import java.util.UUID;

/**
 * 类说明：写数据工具类
 *
 * @author laomo
 * @date 2025/4/22 15:27
 */
public class WriteUtil {
    public static final String TAG = "BleManager";
    public final static int SEND_DATA_MAX_TIMEOUT = 8000; //8 s

    @SuppressLint("MissingPermission")
    public static boolean write(BluetoothGatt gatt, UUID serviceUUID, UUID characteristicUUID, byte[] data) {
        if (gatt == null || null == serviceUUID || null == characteristicUUID || null == data || data.length == 0) {
            JL_Log.d(TAG, "writeDataByBle : 1111111");
            return false;
        }
        BluetoothGattService gattService = gatt.getService(serviceUUID);
        if (null == gattService) {
            JL_Log.d(TAG, "writeDataByBle : 22222");
            return false;
        }
        BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(characteristicUUID);
        if (null == gattCharacteristic) {
            JL_Log.d(TAG, "writeDataByBle : 3333");
            return false;
        }
        boolean ret = false;
        try {
            gattCharacteristic.setValue(data);
            ret = gatt.writeCharacteristic(gattCharacteristic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Log.d(TAG, "writeDataByB :" + ret);
        JL_Log.d(TAG, "writeDataByBle : " + CHexConver.byte2HexStr(data) + ", ret : " + ret + "," + characteristicUUID.toString());
        return ret;
    }
}
